package com.lagou.server.controller;

import com.lagou.server.config.DBConnectionPool;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {

    @GetMapping("/getUsers")
    @ResponseBody
    public String getUsers(){
        try {
            Connection connection = DBConnectionPool.getConnection();
            Statement statement = connection.createStatement();

            //执行sql
            ResultSet rs = statement.executeQuery("select * from public.user");
            List<String> userInfos = new ArrayList<>();
            while (rs.next()) {
                int id = rs.getInt("id");
                String usr_name = rs.getString("username");
                userInfos.add("{\"userName\":\"" + usr_name + ",\"id\":" + id + "}");
            }
            return userInfos.toString();
        } catch (SQLException e) {
            e.printStackTrace();
            return "505: " + e.getMessage();
        }
    }
}
